const express = require('express');
const router = express.Router();

// Get the list of comments
router.get('/comments/:id', 
    async (req, res, next) => {
        if(!req.params.id) {
            return next('route');
        }

        const theStd = await res.app.models.standards_in_dev.findOne({
            id: req.params.id,
        }, {
            意见批次: 1,
        }).lean();

        if (!theStd) {
            res.makeError(402, 'The standard does not exist', router.mdl);
            return next('route');
        }

        res.locals.filter = {
            ...res.locals.filter,
            Board: 'stddev',
            Topic: req.params.id,
            批次: theStd.意见批次 || '默认批',
        };

        // users without audit permission only can see the comments by themselves
        if(req.user.Permission !== '*' && !Object.nestValue(req.user.Permission, 'standards_in_dev.3.save.has')) {
            res.locals.filter.User = req.user.id;
        }

        res.locals.fields = [
            'id',
            'User',
            'Content',
            'CommentTo',
            'LastUpdateDate',
        ];

        res.locals.options = {
            sort: {
                LastUpdateDate: 1,
            },
            populate: [
                {
                    path: 'User',
                    select: 'UserName PhoneNumber Profile.Name Profile.Title Profile.NickName Profile.Avatar Profile.CompanyName',
                },
                {
                    path: 'CommentTo',
                    select: 'id User',
                    populate: {
                        path: 'User',
                        select: 'UserName PhoneNumber Profile.Name Profile.Title Profile.NickName Profile.Avatar Profile.CompanyName',
                    },
                },
            ],
        };

        return next();
    },
    router.FindAllDocuments('forum_comments', false, (req, res) => {
        for (let i = 0; i < res.locals.data.docs.length; i++) {
            const doc = res.locals.data.docs[i];
            doc.User = doc.User._doc || doc.User;

            if (!doc.User) {
                continue;
            }

            const userCompany = doc.User.Profile && doc.User.Profile.CompanyName;
            const userDisplyName = (doc.User.Profile && (doc.User.Profile.NickName || doc.User.Profile.Name || doc.User.Profile.Title)) || doc.User.UserName || doc.User.PhoneNumber;
            doc.UserName = userCompany ? `${userCompany} - ${userDisplyName}` : userDisplyName;

            if(doc.User.Profile && doc.User.Profile.Avatar) {
                const avatar = doc.User.Profile.Avatar;
                doc.UserAvatar = avatar.id || avatar;
            }

            delete doc.User;
            delete doc._id;

            // process comment to user
            if(doc.CommentTo && doc.CommentTo.User) {
                doc.CommentTo = doc.CommentTo._doc || doc.CommentTo;
                doc.CommentTo.User = doc.CommentTo.User._doc || doc.CommentTo.User;

                const ctUserCompany = doc.CommentTo.User.Profile && doc.CommentTo.User.Profile.CompanyName;
                const ctUserDisplyName = (doc.CommentTo.User.Profile && (doc.CommentTo.User.Profile.NickName || doc.CommentTo.User.Profile.Name || doc.CommentTo.User.Profile.Title)) || doc.CommentTo.User.UserName || doc.CommentTo.User.PhoneNumber;
                doc.CommentTo.UserName = ctUserCompany ? `${ctUserCompany} - ${ctUserDisplyName}` : ctUserDisplyName;

                if(doc.CommentTo.User.Profile && doc.CommentTo.User.Profile.Avatar) {
                    const avatar = doc.CommentTo.User.Profile.Avatar;
                    doc.CommentTo.UserAvatar = avatar.id || avatar;
                }

                delete doc.CommentTo._id;
                delete doc.CommentTo.User;
            }
        }
    }),
);

// Create a new comment
router.post('/comments',
    async (req, res, next) => {
        const { id, comment } = req.body;
        const theStd = await res.app.models.standards_in_dev.findOne({ 
            id,
        }).lean();

        if(!theStd) {
            res.makeError(402, 'The standard does not exist', router.mdl);
            return next('route');
        }
        
        res.locals.body = {
            Board: 'stddev',
            Topic: id,

            User: req.user.id,
            Content: comment,

            标委会: theStd.标委会,
            批次: theStd.意见批次 || '默认批',
        };
        return next();
    },
    router.CreateDocument('forum_comments'),
);

// delete a comment
router.delete('/comments',
    (req, res, next) => {
        const { id } = req.body;

        res.locals.filter = {
            ...res.locals.filter,
            Board: 'stddev',
            User: req.user.id,
            id,
        };

        // TODO: check if the user is the super admin
        // TODO: html content from end user, need to be sanitized!!

        return next();
    },
    router.DeleteDocument('forum_comments'),
);

// update a comment
router.put('/comments',
    (req, res, next) => {
        const { id, comment } = req.body;

        res.locals.filter = {
            ...res.locals.filter,
            Board: 'stddev',
            User: req.user.id,
            id,
        };

        // TODO: check if the user is the super admin
        // TODO: html content from end user, need to be sanitized!!

        res.locals.body = {
            Content: comment,
        };
        
        return next();
    },
    router.UpdateDocument('forum_comments'),
);

// reply a comment
router.post('/comments/reply',
    async (req, res, next) => {
        const { id, comment } = req.body;
        const theComment = await res.app.models.forum_comments.findOne({
            ...res.locals.filter,
            id,
            Board: 'stddev',
        }).lean();

        // TODO: check if the user is the super admin
        // TODO: html content from end user, need to be sanitized!!

        if(!theComment) {
            return next('route');
        }

        res.locals.body = {
            Board: 'stddev',
            Topic: theComment.Topic,
            User: req.user.id,
            Content: comment,
            CommentTo: id,
            标委会: theComment.标委会,
            批次: theComment.批次,
        };

        return next();
    },
    router.CreateDocument('forum_comments'),
);

module.exports = router;
